"""
数据库重置脚本
删除所有数据库数据，重新创建默认用户数据和默认权限数据
"""
import asyncio
from motor.motor_asyncio import AsyncIOMotorClient
from app.core.config import settings
from app.core.security import get_password_hash
from app.core.permissions import get_permissions_for_role
from app.models.user import UserRole, UserStatus
from datetime import datetime
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

async def reset_database():
    """重置数据库"""
    # 连接数据库
    client = AsyncIOMotorClient(settings.MONGODB_URL)
    db = client[settings.MONGODB_DATABASE]
    
    try:
        logger.info("开始重置数据库...")
        
        # 1. 删除所有集合的数据
        collections_to_clear = [
            "users",           # 用户
            "projects",        # 项目
            "tasks",           # 任务
            "defects",         # 缺陷
            "requirements",    # 需求
            "versions",        # 版本
            "activities",      # 活动记录
            "notifications",   # 通知
            "roles",           # 角色
            "priorities",      # 优先级
            "stats",           # 统计数据
            # 版本关联表
            "version_task_relations",
            "version_defect_relations", 
            "version_requirement_relations",
            "release_records",
            # 其他可能的集合
            "work_logs",       # 工作日志
            "comments",        # 评论
            "attachments",     # 附件
            "project_templates", # 项目模板
        ]
        
        for collection_name in collections_to_clear:
            try:
                result = await db[collection_name].delete_many({})
                logger.info(f"已清空集合 {collection_name}，删除了 {result.deleted_count} 条记录")
            except Exception as e:
                logger.warning(f"清空集合 {collection_name} 时出错: {e}")
        
        logger.info("数据库清空完成")
        
        # 2. 创建默认优先级数据
        await create_default_priorities(db)
        
        # 3. 创建默认用户数据
        await create_default_users(db)
        
        # 4. 创建默认项目数据（可选）
        await create_default_projects(db)
        
        logger.info("数据库重置完成！")
        
    except Exception as e:
        logger.error(f"重置数据库失败: {e}")
        import traceback
        traceback.print_exc()
    finally:
        client.close()

async def create_default_users(db):
    """创建默认用户数据"""
    logger.info("开始创建默认用户...")
    
    # 创建管理员用户
    admin_user = {
        "username": "admin",
        "name": "系统管理员",
        "email": "admin@example.com",
        "hashed_password": get_password_hash("123456"),
        "status": UserStatus.ACTIVE,
        "is_verified": True,
        "roles": [UserRole.ADMIN],
        "permissions": get_permissions_for_role(UserRole.ADMIN),
        "department": "IT部门",
        "position": "系统管理员",
        "phone": "13800138000",
        "avatar": None,
        "bio": "系统默认管理员账户",
        "created_at": datetime.utcnow(),
        "updated_at": datetime.utcnow(),
        "last_login": None,
        "login_count": 0,
        "is_active": True,
        "settings": {
            "theme": "light",
            "language": "zh-CN",
            "timezone": "Asia/Shanghai",
            "email_notifications": True,
            "push_notifications": True
        }
    }
    
    result = await db.users.insert_one(admin_user)
    logger.info(f"管理员用户创建成功，ID: {result.inserted_id}")
    
    # 创建项目经理用户
    pm_user = {
        "username": "pm",
        "name": "项目经理",
        "email": "pm@example.com",
        "hashed_password": get_password_hash("123456"),
        "status": UserStatus.ACTIVE,
        "is_verified": True,
        "roles": [UserRole.PROJECT_MANAGER],
        "permissions": get_permissions_for_role(UserRole.PROJECT_MANAGER),
        "department": "产品部门",
        "position": "项目经理",
        "phone": "13800138001",
        "avatar": None,
        "bio": "负责项目管理和协调",
        "created_at": datetime.utcnow(),
        "updated_at": datetime.utcnow(),
        "last_login": None,
        "login_count": 0,
        "is_active": True,
        "settings": {
            "theme": "light",
            "language": "zh-CN",
            "timezone": "Asia/Shanghai",
            "email_notifications": True,
            "push_notifications": True
        }
    }
    
    result = await db.users.insert_one(pm_user)
    logger.info(f"项目经理用户创建成功，ID: {result.inserted_id}")
    
    # 创建开发者用户
    dev_user = {
        "username": "developer",
        "name": "开发工程师",
        "email": "dev@example.com",
        "hashed_password": get_password_hash("123456"),
        "status": UserStatus.ACTIVE,
        "is_verified": True,
        "roles": [UserRole.DEVELOPER],
        "permissions": get_permissions_for_role(UserRole.DEVELOPER),
        "department": "技术部门",
        "position": "高级开发工程师",
        "phone": "13800138002",
        "avatar": None,
        "bio": "负责系统开发和维护",
        "created_at": datetime.utcnow(),
        "updated_at": datetime.utcnow(),
        "last_login": None,
        "login_count": 0,
        "is_active": True,
        "settings": {
            "theme": "dark",
            "language": "zh-CN",
            "timezone": "Asia/Shanghai",
            "email_notifications": True,
            "push_notifications": False
        }
    }
    
    result = await db.users.insert_one(dev_user)
    logger.info(f"开发者用户创建成功，ID: {result.inserted_id}")
    
    # 创建测试工程师用户
    tester_user = {
        "username": "tester",
        "name": "测试工程师",
        "email": "tester@example.com",
        "hashed_password": get_password_hash("123456"),
        "status": UserStatus.ACTIVE,
        "is_verified": True,
        "roles": [UserRole.TESTER],
        "permissions": get_permissions_for_role(UserRole.TESTER),
        "department": "质量部门",
        "position": "高级测试工程师",
        "phone": "13800138003",
        "avatar": None,
        "bio": "负责系统测试和质量保证",
        "created_at": datetime.utcnow(),
        "updated_at": datetime.utcnow(),
        "last_login": None,
        "login_count": 0,
        "is_active": True,
        "settings": {
            "theme": "light",
            "language": "zh-CN",
            "timezone": "Asia/Shanghai",
            "email_notifications": True,
            "push_notifications": True
        }
    }
    
    result = await db.users.insert_one(tester_user)
    logger.info(f"测试工程师用户创建成功，ID: {result.inserted_id}")
    
    # 创建查看者用户
    viewer_user = {
        "username": "viewer",
        "name": "项目查看者",
        "email": "viewer@example.com",
        "hashed_password": get_password_hash("123456"),
        "status": UserStatus.ACTIVE,
        "is_verified": True,
        "roles": [UserRole.VIEWER],
        "permissions": get_permissions_for_role(UserRole.VIEWER),
        "department": "业务部门",
        "position": "业务分析师",
        "phone": "13800138004",
        "avatar": None,
        "bio": "负责业务需求分析和项目跟踪",
        "created_at": datetime.utcnow(),
        "updated_at": datetime.utcnow(),
        "last_login": None,
        "login_count": 0,
        "is_active": True,
        "settings": {
            "theme": "light",
            "language": "zh-CN",
            "timezone": "Asia/Shanghai",
            "email_notifications": False,
            "push_notifications": False
        }
    }
    
    result = await db.users.insert_one(viewer_user)
    logger.info(f"查看者用户创建成功，ID: {result.inserted_id}")
    
    # 创建一个被禁用的用户用于测试
    disabled_user = {
        "username": "disabled",
        "name": "禁用用户",
        "email": "disabled@example.com",
        "hashed_password": get_password_hash("123456"),
        "status": UserStatus.INACTIVE,
        "is_verified": True,
        "roles": [UserRole.VIEWER],
        "permissions": get_permissions_for_role(UserRole.VIEWER),
        "department": "测试部门",
        "position": "测试账户",
        "phone": "13800138005",
        "avatar": None,
        "bio": "用于测试禁用状态的账户",
        "created_at": datetime.utcnow(),
        "updated_at": datetime.utcnow(),
        "last_login": None,
        "login_count": 0,
        "is_active": False,
        "settings": {
            "theme": "light",
            "language": "zh-CN",
            "timezone": "Asia/Shanghai",
            "email_notifications": False,
            "push_notifications": False
        }
    }
    
    result = await db.users.insert_one(disabled_user)
    logger.info(f"禁用用户创建成功，ID: {result.inserted_id}")
    
    logger.info("默认用户创建完成")
    logger.info("=" * 50)
    logger.info("默认用户登录信息:")
    logger.info("管理员 - 用户名: admin, 邮箱: admin@example.com, 密码: 123456")
    logger.info("项目经理 - 用户名: pm, 邮箱: pm@example.com, 密码: 123456")
    logger.info("开发者 - 用户名: developer, 邮箱: dev@example.com, 密码: 123456")
    logger.info("测试工程师 - 用户名: tester, 邮箱: tester@example.com, 密码: 123456")
    logger.info("查看者 - 用户名: viewer, 邮箱: viewer@example.com, 密码: 123456")
    logger.info("禁用用户 - 用户名: disabled, 邮箱: disabled@example.com, 密码: 123456 (已禁用)")
    logger.info("=" * 50)

async def create_default_projects(db):
    """创建默认项目数据（可选）"""
    logger.info("开始创建默认项目...")
    
    # 获取管理员用户ID
    admin_user = await db.users.find_one({"username": "admin"})
    if not admin_user:
        logger.warning("未找到管理员用户，跳过创建默认项目")
        return
    
    admin_id = admin_user["_id"]
    
    # 创建示例项目
    demo_project = {
        "name": "项目管理系统演示项目",
        "description": "这是一个用于演示项目管理系统功能的示例项目",
        "category": "web",
        "priority": "high",
        "status": "active",
        "start_date": datetime.utcnow(),
        "end_date": None,
        "estimated_hours": 160,
        "budget": 50000.0,
        "tags": ["演示", "示例", "项目管理"],
        "is_public": True,
        "organization_id": None,
        "members": [
            {
                "user_id": admin_id,
                "role": "owner",
                "joined_at": datetime.utcnow(),
                "permissions": ["project:read", "project:update", "project:delete", "project:manage_members"]
            }
        ],
        "created_by": admin_id,
        "created_at": datetime.utcnow(),
        "updated_at": datetime.utcnow(),
        "is_archived": False
    }
    
    result = await db.projects.insert_one(demo_project)
    logger.info(f"示例项目创建成功，ID: {result.inserted_id}")
    
    logger.info("默认项目创建完成")

async def create_default_priorities(db):
    """创建默认优先级数据"""
    logger.info("开始创建默认优先级数据...")

    # 检查priorities集合是否存在，如果不存在则创建
    if "priorities" not in await db.list_collection_names():
        await db.create_collection("priorities")
        logger.info("创建了 priorities 集合")

    # 模块类型枚举
    class ModuleType:
        PROJECT = "project"
        REQUIREMENT = "requirement"
        TASK = "task"
        DEFECT = "defect"

    # 定义各模块的优先级
    priority_definitions = {
        ModuleType.PROJECT: [
            {"name": "低", "code": "low", "color": "#67C23A", "sort_order": 1},
            {"name": "中", "code": "medium", "color": "#E6A23C", "sort_order": 2, "is_default": True},
            {"name": "高", "code": "high", "color": "#F56C6C", "sort_order": 3}
        ],
        ModuleType.REQUIREMENT: [
            {"name": "低", "code": "low", "color": "#67C23A", "sort_order": 1},
            {"name": "中", "code": "medium", "color": "#E6A23C", "sort_order": 2, "is_default": True},
            {"name": "高", "code": "high", "color": "#F56C6C", "sort_order": 3},
            {"name": "紧急", "code": "urgent", "color": "#F56C6C", "sort_order": 4},
            {"name": "严重", "code": "critical", "color": "#F56C6C", "sort_order": 5}
        ],
        ModuleType.TASK: [
            {"name": "最低", "code": "lowest", "color": "#909399", "sort_order": 0},
            {"name": "低", "code": "low", "color": "#67C23A", "sort_order": 1},
            {"name": "中", "code": "medium", "color": "#E6A23C", "sort_order": 2, "is_default": True},
            {"name": "高", "code": "high", "color": "#F56C6C", "sort_order": 3},
            {"name": "最高", "code": "highest", "color": "#F56C6C", "sort_order": 4}
        ],
        ModuleType.DEFECT: [
            {"name": "最低", "code": "lowest", "color": "#909399", "sort_order": 0},
            {"name": "低", "code": "low", "color": "#67C23A", "sort_order": 1},
            {"name": "中", "code": "medium", "color": "#E6A23C", "sort_order": 2, "is_default": True},
            {"name": "高", "code": "high", "color": "#F56C6C", "sort_order": 3},
            {"name": "最高", "code": "highest", "color": "#F56C6C", "sort_order": 4}
        ]
    }

    # 插入优先级数据
    for module_type, priorities in priority_definitions.items():
        for priority in priorities:
            priority_doc = {
                "module_type": module_type,
                "name": priority["name"],
                "code": priority["code"],
                "color": priority["color"],
                "sort_order": priority["sort_order"],
                "is_default": priority.get("is_default", False),
                "is_enabled": True,
                "created_at": datetime.utcnow(),
                "updated_at": datetime.utcnow()
            }
            # 使用 upsert 避免重复插入
            await db.priorities.update_one(
                {"module_type": module_type, "code": priority["code"]},
                {"$set": priority_doc},
                upsert=True
            )
        logger.info(f"为模块 {module_type} 创建/更新了 {len(priorities)} 个优先级。")

    logger.info("默认优先级数据创建完成")

if __name__ == "__main__":
    print("=" * 60)
    print("数据库重置脚本")
    print("=" * 60)
    print("警告：此操作将删除数据库中的所有数据！")
    print("包括：用户、项目、任务、缺陷、需求、版本等所有数据")
    print("=" * 60)
    
    confirm = input("确认要继续吗？请输入 'YES' 来确认: ")
    if confirm != "YES":
        print("操作已取消")
        exit(0)
    
    print("开始重置数据库...")
    asyncio.run(reset_database())
    print("数据库重置完成！")